<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use App\Base\Annotation\Common;
use App\Base\Annotation\EntityInfo;
use App\Repository\DepartmentRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @EntityInfo(name="Department",cnName="部门")
 * @ApiResource()
 * @ORM\Entity(repositoryClass=DepartmentRepository::class)
 */
class Department
{
    /**
     * @Common(cnName="#",listType="text",editType="text")
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"department"})
     */
    private $id;

    /**
     * @Common(cnName="部门名称",listType="text",editType="text",width="")
     * @ORM\Column(type="string", length=255)
     * @Groups({"department"})
     */
    private $name;

    /**
     * @Common(cnName="列表排序",listType="text",editType="text")
     * @ORM\Column(type="integer", nullable=true)
     * @Groups({"department"})
     */
    private $sort;

    /**
     * @Common(cnName="上级部门",listType="text",editType="select",width="300")
     * @ORM\ManyToOne(targetEntity=Department::class, inversedBy="sons")
     * @Groups({"department"})
     */
    private $parent;

    /**
     * @ORM\OneToMany(targetEntity=Department::class, mappedBy="parent")
     * @ORM\OrderBy({"sort"="ASC"})
     * @Groups({"sons"})
     */
    private $sons;

    public function __construct()
    {
        $this->sons = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getSort(): ?int
    {
        return $this->sort;
    }

    public function setSort(?int $sort): self
    {
        $this->sort = $sort;

        return $this;
    }

    public function getParent(): ?self
    {
        return $this->parent;
    }

    public function setParent(?self $parent): self
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * @return Collection|self[]
     */
    public function getSons(): Collection
    {
        return $this->sons;
    }

    public function addSon(self $son): self
    {
        if (!$this->sons->contains($son)) {
            $this->sons[] = $son;
            $son->setParent($this);
        }

        return $this;
    }

    public function removeSon(self $son): self
    {
        if ($this->sons->contains($son)) {
            $this->sons->removeElement($son);
            // set the owning side to null (unless already changed)
            if ($son->getParent() === $this) {
                $son->setParent(null);
            }
        }

        return $this;
    }
}
